package cn.elead.chaos.framework.web.global.cors;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

import cn.elead.chaos.framework.properties.Cross;
import cn.hutool.core.util.ObjectUtil;

/**
 * SpringBoot 中实现跨域访问的方法1
 * <p>
 * 通过 Filter 设置通用的响应头<br>
 * http://toulezu.com/2019/03/05/SpringBoot-CORS-practice/
 * 
 * @author luopeng
 *
 */
@Deprecated
public class CorsFilter extends OncePerRequestFilter  {

	private Cross cross;
	
	// (yaml配置方式)
	public Cross setCross(Cross cross) {
		if (ObjectUtil.isNotNull(cross)) {
			this.cross = cross;
		} else {
			this.cross = new Cross();
		}
		return this.cross;
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws ServletException, IOException {
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		httpServletResponse.setHeader("Access-Control-Allow-Origin", cross.getAccessControlAllowOrigin());
		httpServletResponse.setHeader("Access-Control-Allow-Headers", cross.getAccessControlAllowHeaders());
		httpServletResponse.setHeader("Access-Control-Allow-Credentials", cross.getAccessControlAllowCredentials());
		httpServletResponse.setHeader("Access-Control-Allow-Methods", cross.getAccessControlAllowMethods());
		
		chain.doFilter(request, response);
	}
}
